package com.daxia.ogmall.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daxia.ogmall.dao.TaskDAO;
import com.daxia.ogmall.dto.TaskDTO;
import com.daxia.ogmall.model.Task;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.BeanMapper;

@Service
public class TaskService {
	
	@Autowired
	private TaskDAO taskDAO;
	
	public List<TaskDTO> find(TaskDTO query, Page page) {
		List<Task> models = taskDAO.find(query, page);
		List<TaskDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<TaskDTO> findAll() {
		return this.find(new TaskDTO(), null);
	}
	
	public List<TaskDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new TaskDTO(), page);
	}
	
	public Long create(TaskDTO dto) {
		Task model = new Task();
		toModel(model, dto);
		return taskDAO.create(model);
	}
	
	public TaskDTO load(Long id) {
	    Task model = taskDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(TaskDTO dto) {
		Task model = taskDAO.load(dto.getId());
		toModel(model, dto);
		taskDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				taskDAO.deleteById(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public TaskDTO findOne(TaskDTO query) {
		Task model = taskDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<TaskDTO> toDTOs(List<Task> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<TaskDTO>(0);
		}
		List<TaskDTO> dtos = new ArrayList<TaskDTO>(models.size());
		for (Task model : models) {
	        TaskDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private TaskDTO toDTO(Task model) {
		if (model == null) {
			return null;
		}
		TaskDTO dto = BeanMapper.map(model, TaskDTO.class);
		
		return dto;
	}
	
	private void toModel(Task model, TaskDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<Task> toModels(List<TaskDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<Task>(0);
		}
		List<Task> models = new ArrayList<Task>(dtos.size());
		for (TaskDTO dto : dtos) {
	        Task model = new Task();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
